package com.taptech.doufu.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.R;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.bean.TipInfo;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.event.EventBusCollectUnRead;
import com.taptech.doufu.event.EventBusLoginout;
import com.taptech.doufu.event.EventBusPersonRecommend;
import com.taptech.doufu.listener.ResultTipListener;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.view.SettingsFuntion;
import com.taptech.doufu.ui.view.SharePicPopupWindow;
import com.taptech.doufu.ui.view.TipDialog;
import com.taptech.doufu.umeng.push.PushManager;
import com.taptech.doufu.util.ShareUtil;
import com.taptech.doufu.util.SharedPreferenceUtil;
import com.taptech.doufu.util.UpdateUtil;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;

import org.greenrobot.eventbus.EventBus;

import static com.taptech.doufu.R.id.rl_more_auto_pay;

public class MoreSetActivity extends DiaobaoBaseActivity implements OnClickListener
{
    private RelativeLayout mFeedback;
    private RelativeLayout mClearCache;
    private RelativeLayout mShareUs,layGoMarket;
    private RelativeLayout mAboutUs;
    private RelativeLayout mUpdate, mReset;
    private RelativeLayout rlAutoPay;// 自动购买设置
    private RelativeLayout layYouthModel;

    private SettingsFuntion setting;
    private ImageView notifyFlag,ivRecommend;

    private SharedPreferences mPreferences, settingsPush;
    private SharedPreferences trafficPreference;

    private boolean checkWifi;
    private ConnectivityManager check_net_manager;
    private TextView personal_center_main_logout;
    private View layUserGrade;
    private boolean isPersonRecommend;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more_set);
        settingsPush = SharedPreferenceUtil.settingsPush(this);
        mPreferences = getSharedPreferences(Constant.sharedPre_push, 0);
        trafficPreference = SharedPreferenceUtil.trafficPreferences(this);
        creatUi();
        setting = new SettingsFuntion(this);
    }

    public void creatUi()
    {
        layGoMarket = findViewById(R.id.layGoMarket);
        layYouthModel = findViewById(R.id.layYouthModel);
        layYouthModel.setOnClickListener(this);
        layGoMarket.setOnClickListener(this);
        layUserGrade = findViewById(R.id.layUserGrade);
        layUserGrade.setOnClickListener(this);
        personal_center_main_logout = (TextView) findViewById(R.id.personal_center_main_logout);
        mFeedback = (RelativeLayout) findViewById(R.id.rl_more_feedback);
        mFeedback.setOnClickListener(this);
        mClearCache = (RelativeLayout) findViewById(R.id.rl_more_clear_cache);
        mClearCache.setOnClickListener(this);
        mShareUs = (RelativeLayout) findViewById(R.id.rl_more_share_us);
        mShareUs.setOnClickListener(this);
        mAboutUs = (RelativeLayout) findViewById(R.id.rl_more_about_us);
        mAboutUs.setOnClickListener(this);
        mUpdate = (RelativeLayout) findViewById(R.id.rl_check_update);
        mUpdate.setOnClickListener(this);
        mReset = (RelativeLayout) findViewById(R.id.rl_reset_app);
        mReset.setOnClickListener(this);
        notifyFlag = (ImageView) findViewById(R.id.notify_config);
//        ivRecommend = findViewById(R.id.ivRecommend);
        rlAutoPay = (RelativeLayout) findViewById(rl_more_auto_pay);
        rlAutoPay.setOnClickListener(this);
        findViewById(R.id.rlUserAgreement).setOnClickListener(this);
        findViewById(R.id.rlPrivacyPolicy).setOnClickListener(this);
        findViewById(R.id.rlThreePrivacyPolicy).setOnClickListener(this);
        findViewById(R.id.rlUserPrivacyPolicy).setOnClickListener(this);
        //个性化推荐
        isPersonRecommend = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean("sp_personal_recommend", this, true);
//        if (isPersonRecommend){
//            ivRecommend.setImageResource(R.drawable.icon_push_open);
//        }else{
//            ivRecommend.setImageResource(R.drawable.icon_push_close);
//        }

//        ivRecommend.setOnClickListener(v -> {
//            isPersonRecommend = !isPersonRecommend;
//            DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean("sp_personal_recommend",isPersonRecommend,this);
//            if (isPersonRecommend){
//                ivRecommend.setImageResource(R.drawable.icon_push_open);
//            }else{
//                ivRecommend.setImageResource(R.drawable.icon_push_close);
//            }
//            //更新UI
//            EventBusPersonRecommend eventBusPersonRecommend = new EventBusPersonRecommend();
//            eventBusPersonRecommend.setTag(EventBusPersonRecommend.tag);
//            EventBus.getDefault().post(eventBusPersonRecommend);
//        });


        if (AccountService.getInstance().isNotifyalbe())
        {
            notifyFlag.setImageResource(R.drawable.icon_push_open);
        } else
        {
            notifyFlag.setImageResource(R.drawable.icon_push_close);
        }
        check_net_manager = (ConnectivityManager) getSystemService((CONNECTIVITY_SERVICE));

        // 自动开启/关闭"省流量模式"
        new Thread(() -> {
            while (checkWifi)
            {
                try
                {
                    Thread.sleep(3000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                //判断网络
                if (check_net_manager != null)
                {
                    NetworkInfo wifi = check_net_manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    if (wifi.isConnectedOrConnecting())
                    {//来到wifi下，恢复自动下图片
                        Constant.IS_TRAFFIC_MODE = false;
                    }
                }
            }
        }).start();

    }



    @Override
    protected void onResume() {
        super.onResume();
        if (AccountService.getInstance().isLogin()) {
            personal_center_main_logout.setVisibility(View.VISIBLE);
        } else {
            personal_center_main_logout.setVisibility(View.GONE);
        }
    }

    private void gotAboutUs()
    {
        Intent intent = new Intent();
        intent.setClass(this, AboutUsActivity.class);
        startActivity(intent);
    }



    @Override
    public void onClick(final View v)
    {
        // TODO Auto-generated method stub
        Intent intent = new Intent();

        switch (v.getId())
        {
            case R.id.layGoMarket:
                try{
                    Uri uri = Uri.parse("market://details?id="+getPackageName());
                    Intent intent1 = new Intent(Intent.ACTION_VIEW,uri);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent1);
                }catch(Exception e){
                    Toast.makeText(this, "您的手机没有安装Android应用市场", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
                break;
            case R.id.layYouthModel:
                YouthModelActivity.Companion.startActivity(this);
                break;
            case R.id.layUserGrade:
                if (AccountService.getInstance().isLogin()) {
                    SimpleWeexActivity.startActivity(this,"vue/login/TFUserInfoEditPage.js");
                } else {
                    AccountService.getInstance().jumpToLogin();
                }
                break;
            case R.id.rlUserAgreement:
                intent.setClass(this, BrowseActivity.class);
                intent.putExtra(Constant.URL, "https://api.doufu.douhuayuedu.com/journal/detail?id=794");
                startActivity(intent);
                break;
            case R.id.rlPrivacyPolicy:
                intent.setClass(this, BrowseActivity.class);
                intent.putExtra(Constant.URL, "https://api.doufu.douhuayuedu.com/journal/detail?id=793");
                startActivity(intent);
                break;
            case R.id.rlUserPrivacyPolicy:
                intent.setClass(this, BrowseActivity.class);
                intent.putExtra(Constant.URL, "https://api.douhuawenxue.com/journal/detail?id=1000");
                startActivity(intent);
                break;
            case R.id.rlThreePrivacyPolicy:
                intent.setClass(this, BrowseActivity.class);
                intent.putExtra(Constant.URL, "https://api.douhuawenxue.com/journal/detail?id=999");
                startActivity(intent);
                break;
            case R.id.rl_more_feedback:
                if (AccountService.getInstance().isLogin()) {
                    //反馈
                    Intent intentBack = new Intent(this, BrowseActivity.class);
                    intentBack.putExtra(Constant.URL, "http://api.doufu.la/index.php/help/question");
                    intentBack.putExtra(Constant.TITLE, "");
                    startActivity(intentBack);
                } else {
                    AccountService.getInstance().jumpToLogin();
                }
                break;
            case R.id.rl_more_clear_cache:
                setting.gotoClearCache(v);
                break;

            case R.id.rl_more_share_us:

//                String desc = "我正在 豆花阅读 App 看小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! http://"+Constant.HOST_END_PAST;
//                ShareUtil.Companion.shareText(this,"豆花阅读",desc);
                SharePicPopupWindow menuWindow = new SharePicPopupWindow(this);
                ShareBeansInfo shareInfo = new ShareBeansInfo(ShareBeansInfo.OWN_SHARE_FLAG);
                shareInfo.shareUrl = "http://"+Constant.HOST_END_PAST;
                menuWindow.setShareBeans(shareInfo);
                // 显示窗口
                menuWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                break;
            case R.id.rl_more_about_us:
                gotAboutUs();
                break;
            case R.id.rl_check_update:
                UpdateUtil.userCheckUpdate(this);
                break;
            case R.id.rl_reset_app:
                TipInfo tipInfo = new TipInfo("警告", "该操作会清除离线、消息通知、登录状态等储存内容，确定重置吗？", R.style.updateDialog, "确定", "取消", false);
                tipInfo.setTipListener(new ResultTipListener()
                {
                    @Override
                    public void resultBack(int flag, int type)
                    {
                        if (1 == flag)
                        {
                            //确定是1
                            setting.gotoClearAppData(v);
                        }
                    }
                });
                TipDialog tipDialog = new TipDialog(this, R.style.updateDialog, tipInfo);

                tipDialog.show();
                break;
            case R.id.rl_more_auto_pay:
                if (AccountService.getInstance().isLogin()) {
                    intent.setClass(this, SimpleWeexActivity.class);
                    intent.putExtra(SimpleWeexActivity.INTENT_WEEX_URL_KEY,"vue/personalcenter/TFAutoPay.js");
                    startActivity(intent);
                } else {
                    AccountService.getInstance().jumpToLogin();
                }
                break;
            default:
                break;
        }
    }



    @Override
    public void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();

        setting.isFinish = false;
        checkWifi = false;

    }





    public void logout(View view)
    {
        //清除
        EventBusCollectUnRead.clearUnRead();
        AccountService.getInstance().clearAccount();
        AccountService.getInstance().setAccountBack(true);
        EventBusLoginout eventBusLoginout = new EventBusLoginout();
        eventBusLoginout.setTag(EventBusLoginout.tag);
        EventBus.getDefault().post(eventBusLoginout);
        setResult(8888);
        finish();
    }

    public void changeNotify(View view)
    {
        if (AccountService.getInstance().isLogin())
        {
            boolean flag = !AccountService.getInstance().isNotifyalbe();
            if (flag)
            {
                mPreferences.edit().putString("isnotifyalbe", "t").commit();
                notifyFlag.setImageResource(R.drawable.icon_push_open);
                PushManager.getInstance().addAlias();
            } else
            {
                mPreferences.edit().putString("isnotifyalbe", "f").commit();
                notifyFlag.setImageResource(R.drawable.icon_push_close);
                PushManager.getInstance().deleteAlias();
            }
        } else
        {
            AccountService.getInstance().jumpToLogin();
        }
    }

    public void back(View view)
    {
        onBackPressed();
    }


}
